// https://www.lintcode.com/problem/longest-semi-alternating-substring/

public class Solution {
    /**
     * @param s: the string
     * @return: length of longest semi alternating substring
     */
    public int longestSemiAlternatingSubstring(String s) {
        // write your code here
        List<Integer> ret = new ArrayList<>();
        if (s.length() == 0) {
            return 0;
        }
        int count = 1;
        StringBuilder sb = new StringBuilder();
        sb.insert(0, s.charAt(0));
        s += " "; // 方便处理结束位置
        for (int i = 1; i < s.length(); ++i) {
            if (s.charAt(i) != s.charAt(i - 1)) {
                if (count >= 3) {
                    ret.add(sb.length() - (count - 2)); // 因为之前重复次数会大于3，所以重复的字最多保留2个。
                    sb = new StringBuilder();
                    sb.insert(0, s.charAt(i - 1));
                    sb.insert(1, s.charAt(i - 1));
                } else if (s.charAt(i) == ' ') {
                    ret.add(sb.length());
                }
                count = 1; // 重新计数
            } else {
                ++count; // 更新连续出现字符长度
            }
            sb.insert(sb.length(), s.charAt(i));
        }
        return Collections.max(ret);
    }
}